﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Text;

namespace BookDemo.S09
{
    class S913 : IBookDemo
    {
        public void Main(string[] args)
        {
            _ = new LoggingEventListener();
            var logger = new ServiceCollection()
                .AddLogging(builder => builder.AddEventSourceLogger())
                .BuildServiceProvider()
                .GetRequiredService<ILogger<Program>>();

            var state = new Dictionary<string, object>
            {
                ["ErrorCode"] = 100,
                ["Message"] = "Unhandled exception"
            };

            logger.Log(LogLevel.Error, 1, state, new InvalidOperationException("This is a manually thrown exception."), (_, ex) => ex.Message);
        }
    }
    public class LoggingEventListener : EventListener
    {
        protected override void OnEventSourceCreated(EventSource eventSource)
        {
            if (eventSource.Name == "Microsoft-Extensions-Logging")
            {
                EnableEvents(eventSource, EventLevel.LogAlways);
            }
        }

        protected override void OnEventWritten(EventWrittenEventArgs eventData)
        {
            Console.WriteLine($"Event: {eventData.EventName}");
            for (int index = 0; index < eventData.Payload.Count; index++)
            {
                var element = eventData.Payload[index];
                if (element is object[] || element is IDictionary<string, object>)
                {
                    Console.WriteLine($"{eventData.PayloadNames[index],-16}: { JsonConvert.SerializeObject(element)}");
                    continue;
                }
                Console.WriteLine($"{eventData.PayloadNames[index],-16}: { eventData.Payload[index]}");
            }
            Console.WriteLine();
        }
    }
}
